package com.study.jyg.rxjava2study.crash;

import android.os.Environment;
import android.os.Process;
import android.util.Log;

import com.study.jyg.rxjava2study.BuildConfig;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 　异常管理类
 */
public class CrashHandler implements Thread.UncaughtExceptionHandler {

    private static final String TAG = "CrashHandler";
    private Thread.UncaughtExceptionHandler defaultHandler = null;
    private static final String CRASH_DIR = "crash.log";

    private CrashHandler() {
        init();
    }
    private static class InstanceHold{
        public static CrashHandler instance = new CrashHandler();
    }

    public static CrashHandler getInstance(){
        return InstanceHold.instance;
    }

    public void init(){
        defaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        if (!handleExceptionMessage(e) && defaultHandler != null){
            defaultHandler.uncaughtException(t,e);
        }else {
            try{
                Thread.sleep(3000);
            }catch (InterruptedException ex){
                e.printStackTrace();
            }
            Process.killProcess(Process.myPid());
            System.exit(1);
        }
    }
    public boolean handleExceptionMessage(Throwable e){
        StringWriter sw = new StringWriter();
        sw.append("这是自定义抛异常\n");
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        File file;
        try {
            file = new File(getCrashDir());
            FileWriter fw = new FileWriter(file);
            fw.write(sw.toString());
            fw.close();
        } catch (IOException e1) {
            e1.printStackTrace();
            return false;
        }
        Log.e(TAG, sw.toString());
        pw.close();
        return true;
    }

    public String getCrashDir(){
        StringBuffer buffer = new StringBuffer();
        buffer.append(Environment.getExternalStorageDirectory()+File.separator).append(BuildConfig.APPLICATION_ID).append(getTime()).append(CRASH_DIR);
        return buffer.toString();
    }

    public String getTime(){
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
        String time = format.format(new Date());
        return time;
    }
}
